import Vue from 'vue'
import Router from 'vue-router'
import Env from '../api/env'
import Home from '@/views/Home'
import Questionnaire from '@/views/questionnaire/Questionnaire'
import QuestionnaireEditor from "../views/questionnaire/QuestionnaireEditor";
import Survey from '@/views/survey/survey'
import Login from '@/views/login/Login'

Vue.use(Router);

const routes = [
    {
        path: '/',
        name: 'root',
        redirect: 'home'
    },
    {
        path: '/login',
        name: 'login',
        component: Login,
    },
    {
        path: '/home',
        name: 'home',
        component: Home,
        redirect: '/home/survey',
        children: [
            {
                path: 'questionnaire',
                component: Questionnaire,
                name: 'questionnaire',
            },
            {
                path: 'survey',
                component: Survey,
                name: 'survey'
            }
        ]
    },
    {
        path: '/editor',
        name: 'editor',
        component: QuestionnaireEditor
    }
];

const router = new Router({
    routes // （缩写）相当于 routes: routes
});

router.beforeEach((to, from, next) => {
    if (Env.isDev) {
        sessionStorage.setItem("loginFlag", "isLogin");
    }
    if (to.name !== "login") {
        const loginFlag = sessionStorage.getItem("loginFlag");
        if (loginFlag === "isLogin") {
            next();
        } else {
            next({
                path: '/login'
            })
        }
    } else {
        next();
    }
});

export default router
